package com.monkeys.Utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class RoutesUtil {

    private static final String ak = "OBaGX676fpevyEdOBkxOcqid0MOry1Ev";

    /* 调用了百度地图API，返回值以及可选值还有更多
    * https://lbs.baidu.com/faq/api?title=webapi/guide/webservice-lwrouteplanapi/dirve */


    /* 这里仅仅返回一个距离(km),作为阶段性功能使用 */
    public static Double getDistance(String startLngLat, String endLngLat){
        // startLngLat 格式为 lng,lat; 要有逗号
        Map<String,String> map = new HashMap<>();
        map.put("ak",ak);
        map.put("origin", startLngLat);
        map.put("destination", endLngLat);
        map.put("steps_info", "0");

        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving?", map);
        JSONObject jsonObject = JSONObject.parseObject(json);

        if(!jsonObject.getString("status").equals("0")){
            throw new RuntimeException("请求失败");
        }

        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray routes = result.getJSONArray("routes");
        Integer distance = (Integer) ((JSONObject) routes.get(0)).get("distance");

        return distance / 1000.00;   //(单位km)
    }



    //传入开始地点和终点地点，返回这段路程的所有关键点的经纬度,比如 "103.564266,30.256648",字符串形式
    public static String[] getLngLatList(String startLngLat, String endLngLat) {
        // startLngLat 格式为 lng,lat; 要有逗号
        Map<String, String> map = new HashMap<>();
        map.put("ak", ak);
        map.put("origin", startLngLat);
        map.put("destination", endLngLat);
        map.put("steps_info", "1");

        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving?", map);

        JSONObject jsonObject = JSONObject.parseObject(json);
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray routes = result.getJSONArray("routes");
        JSONObject jsonObjectRoute = (JSONObject) (routes.get(0));


        //获取详细导航内容
        JSONArray steps = jsonObjectRoute.getJSONArray("steps");
        StringBuilder data = new StringBuilder();

        for(int i = 0; i < steps.size(); i++){
            JSONObject stepJSONObject = (JSONObject) steps.get(i);
            data.append(stepJSONObject.getString("path"));
            data.append(";");
        }

        String string = data.toString();

        return string.split(";");
    }
}
